package com.xf.system.exception;

import com.xf.system.response.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author xiefengf
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 请求参数不全
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ApiResult missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        log.error("请求参数不全:【"+e.getMessage()+"】");
        return ApiResult.fail(400,e.getMessage());
    }

    /**
     * 请求参数不全
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("请求参数不全:【"+e.getMessage()+"】");
        return ApiResult.fail(400,e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ApiResult handleBizException(BusinessException e) {
        ErrorCodeAndMessage codeAndMessage = e.getError();
        return ApiResult.fail(codeAndMessage.getCode(),codeAndMessage.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ApiResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ApiResult.fail(500,"系统未知错误，请反馈给管理员");
    }
}
